package edu.cmu.cs.webapp.ioms.actions.user;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.UserDAOImpl;
import edu.cmu.cs.webapp.ioms.models.User;
import edu.cmu.cs.webapp.ioms.ui.wizards.user.UserWizard;
import edu.cmu.cs.webapp.ioms.views.UsersListView;

public class EditUserViewAction implements IViewActionDelegate {
	private User model;
	private UsersListView _view;

	@Override
	public void init(IViewPart view) {
		this._view = (UsersListView) view;

	}

	@Override
	public void run(IAction action) {
		if (this.model != null) {
			UserWizard wizard = new UserWizard(true, model);
			wizard.setWindowTitle("Edit User");
			WizardDialog dialog = new WizardDialog(_view.getViewSite()
					.getShell(), wizard);
			dialog.setBlockOnOpen(true);
			dialog.open();

			int returnCode = dialog.getReturnCode();

			if (returnCode == org.eclipse.jface.window.Window.OK) {
				try {
					new UserDAOImpl().updateUser(wizard.getModel());
				} catch (DataAccessException e) {
					e.printStackTrace();
				}
			} else {
			}

			this._view.refreshUsersView();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof User) {
				this.model = (User) obj;
			}
		}
	}

}
